package leetcode_core.leetcode_2;

import java.util.Arrays;

public class ThreeSumClosest {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int result = nums[0] + nums[1] + nums[2];
        for(int i = 0 ;i<nums.length-2;i++){
            int left = i+1,right = nums.length-1;
            while (left < right){
                int sum = nums[i] + nums[left] + nums[right];
                int leftVal = nums[left],rightVal=nums[right];
                if(sum == target){
                    return sum;
                }
                if(Math.abs(sum - target) < Math.abs(result - target)){
                    result = sum;
                }
                if(sum < target){
                    left ++ ;
                    while (left <right && nums[left] == leftVal){
                        left ++;
                    }
                }
                if(sum >target){
                    right--;
                    while (left < right && nums[right] == rightVal){
                        right--;
                    }
                }
            }
            if(i< nums.length-2 && nums[i] == nums[i+1]){
                i++;
            }
        }
        return result;
    }
}
